package main

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"io"
	"log"
	"sheetMapper/enums"
)

func main() {

	myApp := app.NewWithID("com.maximus.sheepMapper")
	myWindow := myApp.NewWindow("转换工具")

	label := widget.NewLabel("请选择转换类型")

	ct1, ct2, ct3 := enums.NONE, enums.NONE, enums.NONE

	checkJava := widget.NewCheck("Java", func(value bool) {
		log.Println("Check set to", value)
		if value {
			ct1 = enums.Java
		}
	})

	checkMySql := widget.NewCheck("Mysql", func(value bool) {
		log.Println("Check set to", value)
		if value {
			ct2 = enums.MySQL
		}
	})

	checkOracle := widget.NewCheck("Oracle", func(value bool) {
		log.Println("Check set to", value)
		if value {
			ct3 = enums.ORACLE
		}
	})

	str := binding.NewString()
	str.Set("待转换...")

	resultEntry := widget.NewMultiLineEntry()
	resultEntry.Bind(str)
	resultEntry.AcceptsTab()
	//resultEntry.SetMinRowsVisible(20)

	//content := container.New(
	//    layout.NewVBoxLayout(),
	//    container.New(layout.NewHBoxLayout(), label, checkJava, checkMySql, checkOracle, widget.NewButton("Save", func() {
	//        showFilePicker(myWindow, str, ct1, ct2, ct3)
	//    })),
	//    container.New(layout.NewHBoxLayout(), resultEntry))

	content := container.NewBorder(
		container.New(layout.NewHBoxLayout(), label, checkJava, checkMySql, checkOracle, widget.NewButton("选择文件", func() {
			showFilePicker(myWindow, str, ct1, ct2, ct3)
		})),
		nil,
		nil,
		nil,
		resultEntry,
	)

	myWindow.SetContent(content)
	myWindow.Resize(fyne.NewSize(1000, 1000))

	myWindow.ShowAndRun()

}

func showFilePicker(parent fyne.Window, str binding.String, types ...enums.ConversionType) {
	dialog.ShowFileOpen(func(reader fyne.URIReadCloser, err error) {
		if err != nil {
			log.Println("Error opening file:", err)
			return
		}
		if reader == nil {
			log.Println("No file selected")
			return
		}
		// 处理选中的文件，例如读取或上传
		handleFile(reader, str, types...)
	}, parent)
}

func handleFile(reader fyne.URIReadCloser, str binding.String, types ...enums.ConversionType) {
	defer reader.Close()
	_, err := io.ReadAll(reader)
	if err != nil {
		log.Println("Error reading file:", err)
		return
	}
	fileName := reader.URI().Path()
	var ts string
	for _, t := range types {
		log.Println(t)
		if t == enums.MySQL {
			ts += ToMysql(fileName)
		} else if t == enums.Java {
			ts += ToJava(fileName)
		} else if t == enums.ORACLE {
			ts += ToOracle(fileName)
		}

	}
	str.Set(ts)
	// 实际应用中，这里可以将data发送到服务器等操作
}
